//item
var item = [
[ 0, 1, 0, 0, 0],
[ 1, 1, 0, 0, 1],
[ 0, 1, 1, 1, 0],
[ 0, 1, 1, 1, 0],
[ 0, 1, 0, 1, 0], ];

var Map = new Array();
Map = [
[[ 0, 1, 0, 0, 0],
[ 1, 1, 0, 0, 1],
[ 0, 1, 1, 1, 0],
[ 0, 1, 1, 1, 0],
[ 0, 1, 0, 1, 0]
],

[
[1,1,1,1,1],
[1,0,1,0,1],
[0,1,1,1,0],
[1,1,0,1,1],
[1,1,1,1,1] 
],

[
[0,0,1,0,0],
[0,1,1,1,0],
[0,1,1,1,0],
[1,1,1,1,1],
[0,0,1,0,0]
],

[
[ 0, 0, 1, 1, 0],
[ 1, 0, 1, 0, 0],
[ 1, 1, 0, 1, 1],
[ 0, 0, 1, 0, 1],
[ 0, 1, 1, 0, 0]
],

[
[1,	1,	1,	1,	1],
[0,	0,	1,	0,	0],
[1,	1,	1,	1,	1],
[0,	0,	1,	0,	0],
[1,	1,	1,	1,	1]
]
];

/*
// 멍멍이
var Level1_Map = [
[ 0, 1, 0, 0, 0],
[ 1, 1, 0, 0, 1],
[ 0, 1, 1, 1, 0],
[ 0, 1, 1, 1, 0],
[ 0, 1, 0, 1, 0], ];



// 전화기
var Level2_Map = [
[1,1,1,1,1],
[1,0,1,0,1],
[0,1,1,1,0],
[1,1,0,1,1],
[1,1,1,1,1], ];

// 종
var Level3_Map = [
[0,0,1,0,0],
[0,1,1,1,0],
[0,1,1,1,0],
[1,1,1,1,1],
[0,0,1,0,0], ];

// 바람개비
var Level4_Map = [
[ 0, 0, 1, 1, 0],
[ 1, 0, 1, 0, 0],
[ 1, 1, 0, 1, 1],
[ 0, 0, 1, 0, 1],
[ 0, 1, 1, 0, 0],
];

// 王
var Level5_Map = [
[1,	1,	1,	1,	1],
[0,	0,	1,	0,	0],
[1,	1,	1,	1,	1],
[0,	0,	1,	0,	0],
[1,	1,	1,	1,	1],
];
*/

/* TopScore 저장하기 위한 구조체 */
function Topscore()
{
	var _name;
	var _time;
}

var User_Play = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0], ];

var x =0;
var y =0;

var Complete=0;           
var timer;                //시간잴대 타이머
var P_INTERVAL=10;        //타이머의 보여질 시간
var timmerId;             //타이머의 ID
var arrTime=new Array();  //시간이 기록되는 배열

var topc= 210;		//가로의 위아래 컨트롤
var leftc= 600;		//세로의 왼쪽오른쪽 컨트롤

var match_width = [0, 0, 0, 0, 0]; //세로줄 맞는지 확인
var match_height= [0, 0, 0, 0, 0]; //가로줄 맞는지 확인

var sagak_min = 15; // 5*5는 15분-_-
var sagak_sec = sagak_min * 60 ; //초단위로 환산하자
var timerchecker = null; //일단null
var curTime;
var pauseFlag=0;
var popEXIT=0;
var yEXIT=0;
var popBefore=0;
var yBefore=0;
var popGameOver=0;
var popStageClear=0;

var _topscore = new Array();		// 스코어 저장하기 위한 배열

var stage = 0;   	// 스테이지

var timeupitem=3;
var hintitem=3;
var stageState=[0, 0, 0, 0, 0];

$(document).ready( function() {
	$("#ready").animate({left:50}, "slow");  
	//document.getElementById('minUP').style.visibility="visible"; 
	$("#ready").animate({left:300}, "slow");
	document.getElementById('ready').style.visibility="visible";
	$("#ready").fadeOut("slow");  
	/*
	if(location.search){
		str1=location.search.split("@")[0];
		stage=location.search.split("@")[1];
	}
	*/
	for(i = 0; i < 5; i++) {
		for(j = 0; j < 5; j++) {
			item[i][j] = Map[stage][i][j];
		}
	}
	//givemeRank();
	sagakTimer();
	
	$("#focus0").focus();
	$("#focus0").css({borderColor:'red', borderStyle:'solid',borderWidth:'1px'});	     
	 
	 SetIndex();	
	 
	 Main.createInputObjects();
	 
	 initTopScore();
	 readTopScore(stage);	// stage 0일때
	 addTopScore();
	 setItem(timeupitem,hintitem);
	 
	 Player.init();
	 Audio.init();
});
		
var str1;

function givemeRank(){ //랭킹을 받아오자
	
	$.ajax ({
		type: "post"
		, url: "./ScoreServlet"
		, contentType:"application/x-www-form-urlencoded; charset=UTF-8"
		, dataType:'jsonp'
		, jsonp:'callback'
		, data: "kind=ranking"
		, success: function (response, status, result) {
			
			var plist = eval(response);
			var content = '<tr><td class="list-title"><span class="list-section" >Rank</span></td><td class="list-title"><span class="list-section" >Name</span></td><td class="list-title"><span class="list-section" >Score</span></td></tr>';
			for(var i=0; i<plist.length;i++){
				content+='<tr><td class="list-title"><span class="list-section" >'+eval(i+1)+'</span></td><td class="list-title"><span class="list-section" >'+plist[i].username+'</span></td><td class="list-title"><span class="list-section" >'+plist[i].score+'</span></td></tr>';
			}
			
			$("#table_ranking").html(content);
		}
		, error : function(request, status, error) {
			//통신 에러 발생시 처리
			alert("code : " + request.status + "\r\nmessage : " + request.reponseText);
		}
	});
}
function sound_effect(name)
{
			Player.stopVideo();
			var videoURLs = [ ];
			videoURLs="$WIDGET/sound/"+name+".wav";
			//get URL
			Player.setVideoURL(videoURLs);	//path modify!!
			Player.playVideo();
}

function SetIndex()
{
	for(i=0;i<5;i++) {
		var inHTML_W = "<div valign=bottom align=center><font color='COLOR'>";
		if(match_width[i] == 1)
			inHTML_W = inHTML_W.replace("COLOR", "gray");
		else
			inHTML_W = inHTML_W.replace("COLOR", "black");
		var state = -1; //0:네모 없는 곳, 1 : 네모 있는 곳
		var countnum = 0;
		for(j=0;j<5;j++){
			
			if(state == 1 && Map[stage][j][i] == 0) {
				inHTML_W += countnum + "<br>";
				document.getElementById("text_width"+i).innerHTML = inHTML_W;
				state = 0;
				countnum = 0;
			}
			else if(Map[stage][j][i] == 1) {
				state = 1;
				countnum++;
			}
		}
		if(state == 1)
			inHTML_W += countnum + "<br>";
		else if(state == -1)
			inHTML_W += "<div valign=bottom align=center><font color='gray'>0<br>";
		inHTML_W += "</font></div>"
		document.getElementById("text_width"+i).innerHTML = inHTML_W;
	 }
	 
	 for(i=0;i<5;i++) {
		var inHTML_H = "<div align=right><font color='COLOR'>";
		if(match_height[i] == 1)
			inHTML_H = inHTML_H.replace("COLOR", "gray");
		else
			inHTML_H = inHTML_H.replace("COLOR", "black");
		var state = -1;
		var countnum = 0;
		for(j=0;j<5;j++){
			if(state == 1 && Map[stage][i][j] == 0) {
				inHTML_H += countnum + "&nbsp;&nbsp;&nbsp;";
				document.getElementById("text_height"+i).innerHTML = inHTML_H;
				state = 0;
				countnum = 0;
			}
			else if(Map[stage][i][j] == 1) {
				state = 1;
				countnum++;
			}
		}
		if(state == 1)
			inHTML_H += countnum + "&nbsp;&nbsp;&nbsp;";
		else if(state == -1)
			inHTML_H += "<div align=right><font color='gray'>0&nbsp;&nbsp;&nbsp;";
		inHTML_H += "</font></div>"
		document.getElementById("text_height"+i).innerHTML = inHTML_H;
	 }
}


function Clock()
{
             var time = new Date();
             document.form1.txtClock.value = time.getHours() + " : " + time.getMinutes() + " : " + time.getSeconds();
             timer = setTimeout("Clock()", 1000);//1초마다 Clock함수를 호출.
}



function Stop()
{

             clearTimeout(timer);

}

//타이머
sagakTimer=function() {
	r_min = parseInt(sagak_sec / 60);
	r_sec = sagak_sec % 60;
	
	if(sagak_sec > 0){
	
		switch(r_min){ 
		   case 21:
		            document.getElementById('min').src="../resource/time/21m.png"; break;
		            
		   case 20:
		            document.getElementById('min').src="../resource/time/20m.png"; break;
		            
		   case 19:
		            document.getElementById('min').src="../resource/time/19m.png"; break;
		 
		   case 18:
		            document.getElementById('min').src="../resource/time/18m.png"; break;
		   
		   case 17:
		            document.getElementById('min').src="../resource/time/17m.png"; break;
		   
		   case 16:
		            document.getElementById('min').src="../resource/time/16m.png"; break;
		   
		   case 15:
		            document.getElementById('min').src="../resource/time/15m.png"; break;
		   
		   case 14:
		            document.getElementById('min').src="../resource/time/14m.png"; break;
		   
		   case 13:
		            document.getElementById('min').src="../resource/time/13m.png"; break;
		   
		   case 12:
		            document.getElementById('min').src="../resource/time/12m.png"; break;
		   
		   case 11:
		            document.getElementById('min').src="../resource/time/11m.png"; break;
		   
		    case 10:
		            document.getElementById('min').src="../resource/time/10m.png"; break;
		   
		    case 9:
		            document.getElementById('min').src="../resource/time/09m.png"; break;
		   
		    case 8:
		            document.getElementById('min').src="../resource/time/08m.png"; break;
		   
		    case 7:
		            document.getElementById('min').src="../resource/time/07m.png"; break;
		   
		    case 6:
		            document.getElementById('min').src="../resource/time/06m.png"; break;
		   
		    case 5:
		            document.getElementById('min').src="../resource/time/05m.png"; break;
		   
		    case 4:
		            document.getElementById('min').src="../resource/time/04m.png"; break;
		   
		    case 3:
		            document.getElementById('min').src="../resource/time/03m.png"; break;
		   
		    case 2:
		            document.getElementById('min').src="../resource/time/02m.png"; break;
		   
		    case 1:
		            document.getElementById('min').src="../resource/time/01m.png"; break;
		   
		    case 0:
		            document.getElementById('min').src="../resource/time/00m.png"; break;
	     
		}
	   
	    switch(r_sec){
	    	case 0:
	            document.getElementById('sec').src="../resource/time/00s.png"; break;
	   
	    	case 59:
	            document.getElementById('sec').src="../resource/time/59s.png"; break;
	   
	    	case 58:
	            document.getElementById('sec').src="../resource/time/58s.png"; break;
	   
	    	case 57:
	            document.getElementById('sec').src="../resource/time/57s.png"; break;
	   
	    	case 56:
	            document.getElementById('sec').src="../resource/time/56s.png";	break;
	   
	    	case 55:
	            document.getElementById('sec').src="../resource/time/55s.png";	break;
	   
	    	case 54:
	            document.getElementById('sec').src="../resource/time/54s.png"; break;
	   
	    	case 53:
	            document.getElementById('sec').src="../resource/time/53s.png"; break;
	   
	    	case 52:
	            document.getElementById('sec').src="../resource/time/52s.png";	break;
	   
	    	case 51:
	            document.getElementById('sec').src="../resource/time/51s.png";	break;
	   
	    	case 50:
	            document.getElementById('sec').src="../resource/time/50s.png"; break;
	   
	    	case 49:
	            document.getElementById('sec').src="../resource/time/49s.png"; break;
	   
	    	case 48:
	            document.getElementById('sec').src="../resource/time/48s.png"; break;
	   
	    	case 47:
	            document.getElementById('sec').src="../resource/time/47s.png"; break;
	   
	    	case 46:
	            document.getElementById('sec').src="../resource/time/46s.png"; break;
	   
	    	case 45:
	            document.getElementById('sec').src="../resource/time/45s.png"; break;
	   
	    	case 44:
	            document.getElementById('sec').src="../resource/time/44s.png"; break;
	   
	    	case 43:
	            document.getElementById('sec').src="../resource/time/43s.png"; break;
	   
	    	case 42:
	            document.getElementById('sec').src="../resource/time/42s.png"; break;
	   
	    	case 41:
	            document.getElementById('sec').src="../resource/time/41s.png"; break;
	   
	    	case 40:
	            document.getElementById('sec').src="../resource/time/40s.png"; break;
	   
	    	case 39:
	            document.getElementById('sec').src="../resource/time/39s.png"; break;
	   
	    	case 38:
	            document.getElementById('sec').src="../resource/time/38s.png"; break;
	   
	    	case 37:
	            document.getElementById('sec').src="../resource/time/37s.png"; break;
	   
	    	case 36:
	            document.getElementById('sec').src="../resource/time/36s.png"; break;
	   
	    	case 35:
	            document.getElementById('sec').src="../resource/time/35s.png"; break;
	   
	    	case 34:
	            document.getElementById('sec').src="../resource/time/34s.png"; break;
	   
	    	case 33:
	            document.getElementById('sec').src="../resource/time/33s.png"; break;
	   
	    	case 32:
	            document.getElementById('sec').src="../resource/time/32s.png"; break;
	   
	    	case 31:
	            document.getElementById('sec').src="../resource/time/31s.png"; break;
	   
	    	case 30:
	            document.getElementById('sec').src="../resource/time/30s.png"; break;
	   
	    	case 29:
	            document.getElementById('sec').src="../resource/time/29s.png"; break;
	   
	    	case 28:
	            document.getElementById('sec').src="../resource/time/28s.png"; break;
	   
	    	case 27:
	            document.getElementById('sec').src="../resource/time/27s.png"; break;
	   
	    	case 26:
	            document.getElementById('sec').src="../resource/time/26s.png"; break;
	   
	    	case 25:
	            document.getElementById('sec').src="../resource/time/25s.png"; break;
	   
	    	case 24:
	            document.getElementById('sec').src="../resource/time/24s.png"; break;
	   
	    	case 23:
	            document.getElementById('sec').src="../resource/time/23s.png"; break;
	   
	    	case 22:
	            document.getElementById('sec').src="../resource/time/22s.png"; break;
	   
	    	case 21:
	            document.getElementById('sec').src="../resource/time/21s.png"; break;
	   
	    	case 20:
	            document.getElementById('sec').src="../resource/time/20s.png"; break;
	   
	    	case 19:
	            document.getElementById('sec').src="../resource/time/19s.png"; break;
	   
	    	case 18:
	            document.getElementById('sec').src="../resource/time/18s.png"; break;
	   
	    	case 17:
	            document.getElementById('sec').src="../resource/time/17s.png"; break;
	   
	    	case 16:
	            document.getElementById('sec').src="../resource/time/16s.png"; break;
	   
	    	case 15:
	            document.getElementById('sec').src="../resource/time/15s.png"; break;
	   
	    	case 14:
	            document.getElementById('sec').src="../resource/time/14s.png"; break;
	   
	    	case 13:
	            document.getElementById('sec').src="../resource/time/13s.png"; break;
	   
	    	case 12:
	            document.getElementById('sec').src="../resource/time/12s.png"; break;
	   
	    	case 11:
	            document.getElementById('sec').src="../resource/time/11s.png"; break;
	   
	    	case 10:
	            document.getElementById('sec').src="../resource/time/10s.png"; break;
	   
	    	case 9:
	            document.getElementById('sec').src="../resource/time/09s.png"; break;
	   
	    	case 8:
	            document.getElementById('sec').src="../resource/time/08s.png"; break;
	   
	    	case 7:
	            document.getElementById('sec').src="../resource/time/07s.png"; break;
	   
	    	case 6:
	            document.getElementById('sec').src="../resource/time/06s.png"; break;
	   
	    	case 5:
	            document.getElementById('sec').src="../resource/time/05s.png"; break;
	   
	    	case 4:
	            document.getElementById('sec').src="../resource/time/04s.png"; break;
	   
	    	case 3:
	            document.getElementById('sec').src="../resource/time/03s.png"; break;
	   
	    	case 2:
	            document.getElementById('sec').src="../resource/time/02s.png"; break;
	   
	    	case 1:
	            document.getElementById('sec').src="../resource/time/01s.png"; break;
	     
	    }   
   
	   if(sagak_sec > 0 && pauseFlag==0){
		   sagak_sec--;
		   timerchecker = setTimeout("sagakTimer()", 900); 
	   }
  } 
  else { //남은시간이 0일때 즉 게임오버
	  clearTimeout(timerchecker);
	  document.getElementById('gameover').style.visibility="visible";
	  popGameOver=1;
	  /*이제 여기다가 게임종료됫다는 팝업을*/
  }
 }

/////////////////////////////////진성

function startWatch(obj){ //워치시작
  arrTime.length=0;
  
  arrTime[++arrTime.length-1]=new Date();

  document.myform.txtTimer.value=document.myform.txtTimer.defaultValue;

  timmerId = setInterval('timmer()', P_INTERVAL); //timmer함수를 P_INTERVAL 간격으로 호출함
  
  //document.getElementById('result').innerHTML='';
  //showResult(obj.value);
}


function checkWatch(obj){ //중간중간 기록체크
  arrTime[++arrTime.length-1]=new Date();
  
  showResult(obj.value);
}

function stopWatch(obj){ //스탑워치 종료함

  arrTime[++arrTime.length-1]=new Date();

  clearInterval(timmerId);

  showResult(obj.value);
}

function timmer(){

  var strElapTime  = getElapTime(arrTime[0],new Date());

  document.myform.txtTimer.value=strElapTime;

}


function showResult(strMessage){ //중간중간 스탑워치 기록

  var time = arrTime[arrTime.length-1].toLocaleString();

  var msec = arrTime[arrTime.length-1].getMilliseconds();

  var strElapTime  = getElapTime(arrTime[0],arrTime[arrTime.length-1]);
 
  //document.getElementById('result').innerHTML+=time+'.'+getFixStr(msec,3,0)+' :: elapsed time is '+strElapTime+' '+strMessage+'<br>';

  if(strMessage=="종료") document.myform.txtTimer.value=strElapTime;
}



function getFixStr(strSrc,nLen,strAdd,isFront) { //문자 길이만큼 반환

  strSrc = (strSrc==null)?"" :""+strSrc;
  
  strAdd = (strAdd==null)?" ":""+strAdd;
  
  var nLenBase = strSrc.length;
  
  for(var i=0;i<nLen-nLenBase;i++)
    strSrc = (isFront)?strAdd+strSrc:strSrc+strAdd;
  
  return strSrc;
}

function getElapTime(startTime, endTime){ //시간차이계산해서 경과시간 반환

  var elapTime = new Date();
  
  elapTime.setTime(endTime-startTime);
  
  return getFixStr(elapTime.getUTCHours(),2,0,true)+':'+getFixStr(elapTime.getMinutes(),2,0,true)+':'+getFixStr(elapTime.getSeconds(),2,0,true)+'.'+getFixStr(elapTime.getMilliseconds(),3,0,true);
}

outPause = function(){
	pauseFlag=0;
	sagak_sec = curTime;
	$("#pause").fadeOut("slow");
	document.getElementById('pause').style.visibility="hidden";
	sagakTimer(); //시간을 다시 이어서 구동시키세
}
pauseEvent = function(){
	if(pauseFlag==0) { //정지
		
		curTime = sagak_sec; //pause상태될때의 마지막시간을 저장
		pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
		$("#pause").fadeIn("slow");
		document.getElementById('pause').style.visibility="visible";		
	}
}

//시간 증가
item1 = function(){
	if(!(timeupitem == 0))
	{	
		///////////////
		//sound_effect("time");
		///////////////
	$("#minUP").animate({top:300}, "slow");  
	//document.getElementById('minUP').style.visibility="visible"; 
	$("#minUP").animate({top:-500}, "slow");
	document.getElementById('minUP').style.visibility="visible";
	sagak_sec = sagak_sec + 120; //2분 증가
	setItem(--timeupitem,hintitem);
	}
	else
	{
		///////////////
		//sound_effect("itemno");
		///////////////
	}
}

// 힌트
item2 = function(){
	var num;
	var find;
	/* 개발자 모드 
		document.getElementById('complete').style.visibility="visible";
		document.getElementById("completeSec").innerHTML = "기록:"+ parseInt(sagak_sec/60)+"분"+sagak_sec%60+"초";
		document.getElementById('inputName').style.visibility="visible";
		$("#inputName").focus();
		popStageClear=1;
		pauseFlag=1;
		setClearImage(stage);
		setStageName(stage);
		writeFile(stage);
	*/
	if(!(hintitem ==0))
	{
		///////////////
		//sound_effect("hint");
		///////////////
	for (x = 0; x < 5; x++){			  			
		for (y = 0; y < 5; y++){
			if(item[x][y]==1)
			{	//아직 유저가 못찾아낸 답이구나
				User_Play[x][y]=1;
				item[x][y]=0;
				num= (x*5)+y;
				$("#focus"+num).attr("background","../resource/5x5/Ocheck.png");
				
				find=1;
				$("#hint").fadeTo("slow",0.6); 
				//$("#minDOWN").animate({left:0}, "slow");  
				//$("#minDOWN").animate({top:-500}, "slow");
				document.getElementById('hint').style.visibility="visible"; $("#hint").fadeOut("slow");
				
				var MapTrueCount = 0;
				var UserTrueCount = 0;
				
				for(i=0; i<5; i++) {
					if(Map[stage][x][i] == 1)
						MapTrueCount++;
					if(User_Play[x][i] == 1)
						UserTrueCount++;
				}
				if(MapTrueCount == UserTrueCount)
					match_height[x] = 1;
					
				MapTrueCount = 0;
				UserTrueCount = 0;
				
				for(i=0; i<5; i++) {
					if(Map[stage][i][y] == 1)
						MapTrueCount++;
					if(User_Play[i][y] == 1)
						UserTrueCount++;
				}
				if(MapTrueCount == UserTrueCount)
					match_width[y] = 1;
				
				SetIndex(); //다되면 회색글시로 바껴야 하는데...
				
				stageClear(); //마지막 남은 한칸을 힌트로 맞출수도 있으므로  스테이지 클리어 확인.
				break;   
			}				
		}
		
			if(find==1) break;
	}
	setItem(timeupitem,--hintitem);
	}
	else
	{
		///////////////
		//sound_effect("itemno");
		///////////////		
	}
}

select = function(focus_num){
	var x = document.getElementById('x');
	if(x.checked == false){
	if(focus_num<5)
	{
		if(Map[stage][0][focus_num] == 1 && User_Play[0][focus_num]==0)	// 비어있을때 잘 선택하면
		{
			User_Play[0][focus_num]=1;
			item[0][focus_num]=0;
			$("#focus"+focus_num).attr("background","../resource/5x5/Ocheck.png");
			///////////////
			//sound_effect("ok");
			///////////////
			
			var MapTrueCount = 0;
			var UserTrueCount = 0;
			
			for(i=0; i<5; i++) {
				if(Map[stage][0][i] == 1)
					MapTrueCount++;
				if(User_Play[0][i] == 1)
					UserTrueCount++;
			}
			if(MapTrueCount == UserTrueCount)
				match_height[0] = 1;
				
			
			MapTrueCount = 0;
			UserTrueCount = 0;
			
			for(i=0; i<5; i++) {
				if(Map[stage][i][focus_num] == 1)
					MapTrueCount++;
				if(User_Play[i][focus_num] == 1)
					UserTrueCount++;
			}
			if(MapTrueCount == UserTrueCount)
				match_width[focus_num] = 1;
				
			SetIndex();
		}
		
		else if((Map[stage][0][focus_num] == 0)&&( User_Play[0][focus_num]==0 || User_Play[0][focus_num]==3))	// 비어있거나 빨간 x일때 잘못 선택하면 
		{
			User_Play[0][focus_num]=3;
			$("#focus"+focus_num).attr("background","../resource/5x5/Xred.png");
			
			///////////////
			//sound_effect("no");
			///////////////
			
			
		//시간깎기 및 이펙트
		$("#minDOWN").fadeTo("slow",0.6);  
		//$("#minDOWN").animate({left:0}, "slow");  
		//$("#minDOWN").animate({top:-500}, "slow");
		document.getElementById('minDOWN').style.visibility="visible"; $("#minDOWN").fadeOut("slow");  
		sagak_sec = sagak_sec - 120; //2분 증가
		//////////////
		}
		
		else if(User_Play[0][focus_num] == 2)	// x일때 선택하면
		{
			User_Play[0][focus_num]=0;
			$("#focus"+focus_num).attr("background","../resource/5x5/nothing.png");
		}
		
	}
	else //포커스 5보다 클때
	{
		if(Map[stage][Math.floor(focus_num/5)][focus_num%5] == 1 && User_Play[Math.floor(focus_num/5)][focus_num%5]==0)
		{
			User_Play[Math.floor(focus_num/5)][focus_num%5]=1;
			item[Math.floor(focus_num/5)][focus_num%5]=0;
			$("#focus"+focus_num).attr("background","../resource/5x5/Ocheck.png");
			
			///////////////
			//sound_effect("ok");
			///////////////
			
			
			var MapTrueCount = 0;
			var UserTrueCount = 0;
			
			for(i=0; i<5; i++) {
				if(Map[stage][Math.floor(focus_num/5)][i] == 1)
					MapTrueCount++;
				if(User_Play[Math.floor(focus_num/5)][i] == 1)
					UserTrueCount++;
			}
			if(MapTrueCount == UserTrueCount)
				match_height[Math.floor(focus_num/5)] = 1;
				
			
			MapTrueCount = 0;
			UserTrueCount = 0;
			
			for(i=0; i<5; i++) {
				if(Map[stage][i][focus_num%5] == 1)
					MapTrueCount++;
				if(User_Play[i][focus_num%5] == 1)
					UserTrueCount++;
			}
			if(MapTrueCount == UserTrueCount)
				match_width[focus_num%5] = 1;
				
			SetIndex();
		}
		
		else if((Map[stage][Math.floor(focus_num/5)][focus_num%5] == 0) && (User_Play[Math.floor(focus_num/5)][focus_num%5]==0 || User_Play[Math.floor(focus_num/5)][focus_num%5]==3))
		{
			User_Play[Math.floor(focus_num/5)][focus_num%5]=3;
			$("#focus"+focus_num).attr("background","../resource/5x5/Xred.png");
			
			///////////////
			//sound_effect("no");
			///////////////
			
			
			//시간깎기 및 이펙트
		$("#minDOWN").fadeIn("slow");  
		//$("#minDOWN").animate({left:0}, "slow");  
		//$("#minDOWN").animate({top:-500}, "slow");
		document.getElementById('minDOWN').style.visibility="visible"; $("#minDOWN").fadeOut("slow");  
		sagak_sec = sagak_sec - 120; //2분 증가
		//////////////
		}
		
		else if(User_Play[Math.floor(focus_num/5)][focus_num%5] == 2)
		{
			User_Play[Math.floor(focus_num/5)][focus_num%5]=0;
			$("#focus"+focus_num).attr("background","../resource/5x5/nothing.png");
		}
		
	}
	//alert("test!!!!"+Map[stage][i*10+j]);
	//check the complete
	stageClear();
	}
	else
	{
		if(focus_num<5)
		{
			if(User_Play[0][focus_num]==2)
			{
				User_Play[0][focus_num]=0;
				$("#focus"+focus_num).attr("background","../resource/5x5/nothing.png");
			}
			else if(User_Play[0][focus_num] == 0)
			{
				User_Play[0][focus_num]=2;
				$("#focus"+focus_num).attr("background","../resource/5x5/X.png");
				
				///////////////
				//sound_effect("x");
				///////////////
				
			}
		}
		else
		{
			if(User_Play[Math.floor(focus_num/5)][focus_num%5]==2)
			{
				User_Play[Math.floor(focus_num/5)][focus_num%5]=0;
				$("#focus"+focus_num).attr("background","../resource/5x5/nothing.png");
			}
			else if(User_Play[Math.floor(focus_num/5)][focus_num%5] == 0)
			{
				User_Play[Math.floor(focus_num/5)][focus_num%5]=2;
				$("#focus"+focus_num).attr("background","../resource/5x5/X.png");
				
				
				///////////////
				//sound_effect("x");
				///////////////
				
			}
		}
	}
}

KeyHandler = function()
{
	//엑스에 체크된 상태로 클릭시
	switch(KeyCode)
	{ 
		case tvKey.KEY_LEFT :
	
	//////////////////////////	
		focus_num-=1;
		if(focus_num<0) //focus0에서 왼쪽시 작아져..멍청아
			focus_num+=1;
		
		
		//세로의 움직임... 그리고 가로도
		leftc-=50;
		if(focus_num==0)
		leftc=600;
		else if(focus_num%5==4)
		{
		leftc=600+50*4;
		topc-=48;
		}

			break;
            
			
		case tvKey.KEY_RIGHT :
//////
		if(popEXIT==1){
		document.getElementById('popEXIT').src="../resource/popup/exit_n.png";
		yEXIT=0;
		break;
		}
		
		if(popBefore==1){
		document.getElementById('before').src="../resource/popup/before_n.png";
		yBefore=0;
		break;
		}

		if(pauseFlag==1 || popStageClear == 1) { 
		//alert("포커스못감");
		break;
		}
////////

		focus_num+=1;
		if(focus_num>24)
			focus_num-=1;
		
		
		//세로의 움직임... 그리고 가로도
		leftc+=50;
		if(focus_num==24)
		leftc=600+50*4;
		else if(focus_num%5==0)
		{
		leftc=600;
		topc+=48;
		}
			break;
			
			
		case tvKey.KEY_UP :
		
		if(pauseFlag==1 || popStageClear == 1) { 
		//alert("포커스못감");
		break;
		}
		focus_num-=5;
		if(focus_num<0)
			focus_num+=5;
		
		
		//가로의 움직임...
		topc-=48;
		if(focus_num<=4)
		topc=210;
		
		$("#garo").css("top",topc );
		
			break;
			
		case tvKey.KEY_DOWN :
		
		if(pauseFlag==1 || popStageClear == 1) { 
		//alert("포커스못감");
		break;
		}
		focus_num+=5;
		if(focus_num>24)
			focus_num-=5;
		
		
		//가로의 움직임...
		topc+=48;
		if(focus_num>=20)
		topc=210+48*4;
		
		$("#garo").css("top",topc );
		
			break; 
			
		case tvKey.KEY_ENTER :		

		//////////////////진성진성

		if(popGameOver==1){ //게임오버~	
			window.close();
			window.open("5x5.html?temp="+window.location.search,"logic","width=960,height=540");	
		}
		
        case tvKey.KEY_YELLOW: //timeUp기능 타임업이펙트보여주고 시간 120초 증가

		
        ///////////////////////////////////////////
		
        break;
		
		case tvKey.KEY_GREEN:
		
		if(pauseFlag==1) { 
			window.close();
			window.open("5x5.html?temp="+window.location.search,"logic","width=960,height=540");
		}
		
		else if(popStageClear==1) { 
			window.close();
			window.open("5x5.html?temp="+window.location.search,"logic","width=960,height=540");
		}
		
		
		break;
		
		
		case tvKey.KEY_PAUSE:
		
			
		
		break;
        
        
        case tvKey.KEY_RETURN:
			///////////////
			sound_effect("pause");
			///////////////
			widgetAPI.blockNavigation(event);
            //stopWatch(this); //	
			if(popStageClear == 1)
			{
			}
			else
			{
				if(popGameOver==1){ //게임오버~
					window.close();
					window.open("stage.html?temp="+str1,"logic","width=960,height=540");
				}
				
				if(popEXIT==1) {
				document.getElementById('popEXIT').style.visibility="hidden";
				popEXIT=0;
				pauseFlag=0;
				sagak_sec = curTime;
				sagakTimer(); //시간을 다시 이어서 구동시키세		
				break;
				}
				
				if(popBefore==1) {
				document.getElementById('before').style.visibility="hidden";
				popBefore=0;
				pauseFlag=0;
				sagak_sec = curTime;
				sagakTimer(); //시간을 다시 이어서 구동시키세		
				break;
				}
				
				document.getElementById('before').style.visibility="visible";
				popBefore=1;
				curTime = sagak_sec; //잠시 시간 정지를 위해  마지막시간을 저장
				pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
			}
        break;
        
        case tvKey.KEY_EXIT:
			///////////////
			sound_effect("pause");
			///////////////
			widgetAPI.blockNavigation(event);
			if(popStageClear == 1)
			{
			}
			else
			{
			document.getElementById('popEXIT').style.visibility="visible"; //기본적으로 포커스는 아니오에..
			popEXIT=1;		
			curTime = sagak_sec; //잠시 시간 정지를 위해  마지막시간을 저장
			pauseFlag=1; //멈췃을때는 더이상 1초마다 시간카운트 되지않게 위에서 조절
			}
					
		break;
            
		default :
			break;
	}
	 $("#focus"+focus_num).css({borderColor:'red', borderStyle:'solid',borderWidth:'1px'});
}
/////진성
function stageClear(){ //힌트썼을때도 스테이지 클리어확인, 유저가 직접 맞출때도 각각 호출된디
		
			var i=0;
			var j=0;
			/* 퍼즐을 다 맞췄는지 판별하는 아이 */
			 for (i = 0; i < 5; i++)
			 {			  
				for (j = 0; j < 5; j++)
				{
					
					if(Map[stage][i][j]==1)
					{	
						if(User_Play[i][j]==1)
						{	
							Complete=1;
						}
						else
						{
							Complete=0;
							i = 5;
							break;
						}
					}
								
				}
			}
		
		if(Complete==1)
		{	
			///////////////
			//sound_effect("end");
			///////////////
			
			//document.getElementById('complete').style.visibility="visible";
			//document.getElementById("completeSec").innerHTML = "기록:"+ parseInt(sagak_sec/60)+"분"+sagak_sec%60+"초";
			//document.getElementById('inputName').style.visibility="visible";
			//$("#inputName").focus();
			sagak_sec = 900-sagak_sec;
			alert("축하합니다!!! 기록: " + parseInt(sagak_sec/60)+"분"+sagak_sec%60+"초");
			window.close();
			window.open("stage.html?temp="+window.location.search,"logic","width=960,height=540");
			
			popStageClear=1;
			pauseFlag=1;
			setClearImage(stage);
			setStageName(stage);
			//writeFile(stage);
		}


}


////// 수진 Topscore 구현

function initTopScore()
{
	for(var i=0;i<3;i++)
	{
		_topscore[i] = new Topscore();
		_topscore[i]._name = "";
		_topscore[i]._time = 0;
	}
	
	for(var i=1;i<=3;i++)
	{
		document.getElementById("scorenum" + i).innerHTML = i + ".";
	}
}


function addTopScore()
{
	if(!(_topscore[0]._time == 0))	
	{
		document.getElementById("scorename1").innerHTML = _topscore[0]._name;
		document.getElementById("score1").innerHTML = parseInt(_topscore[0]._time/60) + " : " + _topscore[0]._time%60;
	}
	if(!(_topscore[1]._time == 0))	
	{
		document.getElementById("scorename2").innerHTML = _topscore[1]._name;
		document.getElementById("score2").innerHTML = parseInt(_topscore[1]._time/60) + " : " + _topscore[1]._time%60;
	}
	if(!(_topscore[2]._time == 0))	
	{
		document.getElementById("scorename3").innerHTML = _topscore[2]._name;
		document.getElementById("score3").innerHTML = parseInt(_topscore[2]._time/60) + " : " + _topscore[2]._time%60;
	}
}


checkScore = function(name,score)
{

	if(_topscore[0]._time<score) 
	{
	
		_topscore[2]._name = _topscore[1]._name;
		_topscore[2]._time = _topscore[1]._time;
		
		_topscore[1]._name = _topscore[0]._name;
		_topscore[1]._time = _topscore[0]._time;
	
		_topscore[0]._name = name;
		_topscore[0]._time = score;
	}
	
	else if(_topscore[1]._time<score)
	{
		_topscore[2]._name = _topscore[1]._name;
		_topscore[2]._time = _topscore[1]._time;
		
		_topscore[1]._name = name;
		_topscore[1]._time = score;
	
	}
	else if(_topscore[2]._time<score)
	{
		_topscore[2]._name = name;
		_topscore[2]._time = score;
	}
	
	
}

writeTopScore = function(stage)
{
	var topscoreobj = "";

	for(var i=0; i<3; i++)
    {
        for (var imsi in _topscore[i]) {                                          // 파일에 저장하기 위해 Object의 내용을 파해친 후 personObj에 저장
            topscoreobj += _topscore[i][imsi] + '\n';
        }
        
    }             
        
    var fileSystemObj = new FileSystem(); 
    
   	if (!fileSystemObj.isValidCommonPath(curWidget.id)) {
        fileSystemObj.createCommonDir(curWidget.id);}
        
    var fileObj1 = fileSystemObj.openCommonFile(curWidget.id + '/5x5_' + stage + '.data', 'w');   
    
    if(fileObj1.writeAll(topscoreobj))         // Array에서 받아온 것들을 싸그리 모은 personwriteObj를 왕창 저장 완료시 쓴 내용 표시
    {                                             // 쓴 내용을 표시하는 것은 실제 앱 구동에는 필요 없음
        //alert("파일 쓰기가 완료 되었습니다");
        //alert("-------- 쓰기내용 ---------");
        //alert(topscoreobj);
    }
    
    fileSystemObj.closeCommonFile(fileObj1);

    topscoreobj = '';  
}

readTopScore = function(stage)	// 탑 스코어 읽어오기
{
	var fileSystemObj = new FileSystem(); 

    if (!fileSystemObj.isValidCommonPath(curWidget.id)) {     // Common 폴더 없으면 만들어 줍니다.
    fileSystemObj.createCommonDir(curWidget.id);}
    
    if(!(fileSystemObj.openCommonFile(curWidget.id + '/5x5_' + stage + '.data', 'r') == null))   // 처음 이라면 파일이 없을수가 있죠, 그때는 안불러옵니다.
    {
        fileObj = fileSystemObj.openCommonFile(curWidget.id + '/5x5_' + stage + '.data', 'r');  // 파일 오픈하구요.
        
        var i=0;

            for(i=0;i<3;i++)
            {

                _topscore[i]._name = fileObj.readLine();
				_topscore[i]._time = fileObj.readLine();

            }
      
        fileSystemObj.closeCommonFile(fileObj);                      // 당연히 닫아줘야 해용~~ㅋㅋ
        
    }  
                    
}

setItem = function(timeup,hint)
{
	
	switch(timeup)
	{
		case 0: $("#timeupitem").attr("src","../resource/images/item0.png"); 	break;
		case 1: $("#timeupitem").attr("src","../resource/images/item1.png"); 	break;
		case 2: $("#timeupitem").attr("src","../resource/images/item2.png"); 	break;
		case 3: $("#timeupitem").attr("src","../resource/images/item3.png"); 	break;
	}
	switch(hint)
	{
		case 0: $("#hintitem").attr("src","../resource/images/item0.png"); 	break;
		case 1: $("#hintitem").attr("src","../resource/images/item1.png"); 	break;
		case 2: $("#hintitem").attr("src","../resource/images/item2.png"); 	break;
		case 3: $("#hintitem").attr("src","../resource/images/item3.png"); 	break;
	}
}

setClearImage = function(stage)
{
	$("#clearimage").attr("src","../resource/5x5/5x5clear" + stage + ".png"); 
}

 //스테이지 깼는지 확인하는 파일 불러오기
 readFile = function(){

        var fileSystemObj = new FileSystem(); 

        if (!fileSystemObj.isValidCommonPath(curWidget.id)) {     // Common 폴더 없으면 만들어 줍니다.
            fileSystemObj.createCommonDir(curWidget.id);}
    
        //if(fileSystemObj.openCommonFile(curWidget.id + '/Level5.data', 'r')   // 처음 이라면 파일이 없을수가 있죠, 그때는 안불러옵니다.
        //{
			var fileObj3 = fileSystemObj.openCommonFile(curWidget.id + '/Level0.data', 'r');
			
            for(i=0;i<5;i++)
            {
                stageState[i] = fileObj3.readLine();
            }
			      
			fileSystemObj.closeCommonFile(fileObj3);                      // 당연히 닫아줘야 해용~~ㅋㅋ
			
			
			for(i=0;i<5;i++)
            {
                //alert(stageState[i] + "\n");
            }     
		//}
}


//깬 스테이지 write        
writeFile = function(mapIndex)
{

	//alert("쓰기 들어옴");
	//alert(mapIndex);

	readFile();

	var fileSystemObj1 = new FileSystem(); 
	var mapwriteObj='';
    	
	stageState[mapIndex] = 1;
	
	if (!fileSystemObj1.isValidCommonPath(curWidget.id)) {
		fileSystemObj1.createCommonDir(curWidget.id);}
        
	var fileObj1 = fileSystemObj1.openCommonFile(curWidget.id + '/Level0.data', 'w');   
	
	for(i=0; i<5; i++) {
		mapwriteObj += stageState[i] +'\n';;
	//alert(mapwriteObj);
	}
	//alert("ㅇㅇ");
	if(fileObj1.writeAll(mapwriteObj)) {
		//alert("파일 쓰기가 완료 되었습니다");
        //alert("-------- 쓰기내용 ---------");
        //alert(mapwriteObj);
	}
	else
		//alert("실패");
    
    fileSystemObj1.closeCommonFile(fileObj1);

    mapwriteObj = '';  
            
}

// 수진 추가

setStageName = function (stage)
{
	
	switch(stage)
	{
		case '0': document.getElementById("stagename").innerHTML = "멍멍이"; break;
		case '1': document.getElementById("stagename").innerHTML = "전화기"; break;
		case '2': document.getElementById("stagename").innerHTML = "종"; break;
		case '3': document.getElementById("stagename").innerHTML = "바람개비"; break;
		case '4': document.getElementById("stagename").innerHTML = "王"; break;
	}
}
